package com.bingo.gateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;

@Component
@Slf4j
public class OAuthFilter  extends ZuulFilter {
    public String filterType() {
        return "pre"; //"pre","post","error","route"
    }
    public int filterOrder() {
        return 0;
    }
    //永远起作用
    public boolean shouldFilter() {
        return true;
    }
    public Object run() throws ZuulException {
        log.info("aouth start");
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        if(StringUtils.startsWith(request.getRequestURI(),"/token")){
            return null;
        }
        String authHeader = request.getHeader("Authorization");
        if(StringUtils.isBlank(authHeader)){
            return null;
        }
        if(!StringUtils.startsWithIgnoreCase(authHeader,"Bearer")){
            return null;
        }
        try{
            TokenInfo tokenInfo = getTokenInfo(authHeader);
            request.setAttribute("tokenInfo",tokenInfo);
        }catch (Exception e){
            log.error("system error");
            e.printStackTrace();
        }
        return null;
    }
    private RestTemplate restTemplate = new RestTemplate();
    private TokenInfo getTokenInfo(String authHeader) {
        String token = StringUtils.substringAfter(authHeader,"bearer ");
        String oauthServiceUrl = "http://oauth.bingo.com:8080/oauth/check_token";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.setBasicAuth("gateway","123456");
        MultiValueMap<String,String> params = new LinkedMultiValueMap<String, String>();
        params.add("token",token);
        HttpEntity<MultiValueMap<String,String>> httpEntity = new HttpEntity<MultiValueMap<String, String>>(params,headers);
        ResponseEntity<TokenInfo> responseEntity = restTemplate.exchange(oauthServiceUrl, HttpMethod.POST,httpEntity,TokenInfo.class);
        log.info("token info:"+responseEntity.getBody());
        return responseEntity.getBody();
    }
}
